package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    //通过微信在线体检预约
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        //获取随机4位验证码
        String validateCode = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
        try {
            //发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //将发送成功的验证码保存到redis中5分钟
        Jedis resource = jedisPool.getResource();
        resource.setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 300, validateCode);
        //释放资源
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //通过手机验证码实现快速登录
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        //获取随机6位验证码
        String validateCode = String.valueOf(ValidateCodeUtils.generateValidateCode(6));
        try {
            //发送验证码
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //将发送成功的验证码保存到redis中5分钟
        Jedis resource = jedisPool.getResource();
        resource.setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 300, validateCode);
        //释放资源
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
